package com.coffee.wx.controller;

import cn.hutool.core.util.StrUtil;
import com.coffee.wx.service.IWxService;
import com.coffee.wx.service.IWxUserInfoService;
import jakarta.annotation.Resource;
import jakarta.servlet.http.HttpServletRequest;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.io.IOException;
import java.util.Map;

/**
 * 微信接口
 */
@RestController
@RequestMapping
public class WxController {

    @Resource
    private IWxService wxService;

    @Resource
    private IWxUserInfoService userInfoService;


    /**
     * 微信绑定验证
     *
     * @param signature
     * @param timestamp
     * @param nonce
     * @param echostr
     * @return
     */
    @GetMapping("/wx")
    public String bindCheck(String signature, String timestamp, String nonce, String echostr) {
        String hashedString = wxService.bindCheck(signature, timestamp, nonce, echostr);
        System.out.println("hashedString = " + hashedString);
        if (StrUtil.equals(hashedString, signature)) {
            return echostr;
        } else {
            return null;
        }
    }

    /**
     * 接收消息
     *
     * @param request
     * @return
     * @throws IOException
     */
    @PostMapping("/wx")
    public String receiveMessage(HttpServletRequest request) {

        // 读取请求体中的信息
        Map<String, Object> xml = wxService.readRequestBody(request);

        // 构建响应
        return wxService.buildResponse(xml);
    }

    /**
     * 获取用户信息
     */
    @GetMapping("/getSignUpUserInfo")
    public String getSignUpUserInfo(HttpServletRequest request) {
        return userInfoService.getUserInfo(
                request.getParameter("code"),
                request.getParameter("state")
        );
    }

}
